//该文件用于创建Vuex中最为核心的store
import {reqGetShopCart,reqDeleteCart,reqCheckCart} from '@/api/index'

//准备actions一用于响应组件中的动作
const actions ={
    //获取购物车信息
    async getShopCart({commit}){
         let result = await reqGetShopCart() 
         if(result.code == 200){
            commit("GETSHOPCART",result.data)
         }
    },
    //删除商品请求
    async reqDeleteCart({commit},skuId){
        let result = await reqDeleteCart(skuId)
        if(result.code == 200){
            return 'ok'
        }
    },
    //切换商品选中状态
    async reqCheckCart({commit},{skuId,isChecked}){
        let result = await reqCheckCart(skuId,isChecked)
        if(result.code == 200){
            return 'ok'
        }
    },
    //删除选中全部的商品
    reqAllDeleteCart({getters,dispatch}){  
        let PromiseAll = []  
        getters.cartList.forEach(i => {
            if(i.isChecked == 1){
                let promise = dispatch("reqDeleteCart",i.skuId)
                PromiseAll.push(promise)
            }
        });
        return Promise.all(PromiseAll)
    }
}
//准备mutations.一用于操作数据(state)
const mutations ={
    GETSHOPCART(state,getShopCart){
        state.getShopCart = getShopCart || []
    }
}
//准备state一用于存储数据
const state ={
    getShopCart:[]
}
//getters:理解为计算属性，用于简化仓库数据，让组件获取仓库的数据更加方便
const getters = {
    cartList(state){
        if(state.getShopCart.length == 0){
            return []
        }else{
            return state.getShopCart[0].cartInfoList 
        }
    }
}

//创建并暴露store
export default{
state,
mutations,
actions,
getters,
}